<?php
declare (strict_types = 1);
/**
 * 管理员
 */
namespace app\common\admin;

use think\facade\Db;
use app\common\facade\model\PgmInfoModel; // 引入节目库模型
use app\common\facade\model\PgmInfoPlayModel; //  引入节目播放信息模型
use app\common\facade\model\AdvPgmInfoModel;  // 引入广告库模型
use app\common\facade\model\ChannelInfoModel;
use app\common\facade\model\PgmGroupModel;
use app\common\facade\model\PgmGroupDetailModel;
use app\common\facade\model\PgmInfoPlanModel; 
use app\common\facade\model\PgmInfoDetailModel;

class PgmManage extends BaseAdmin
{
    /**
     * 素材列表
     */
    public function pgmlibList($param = [])
    {
        $where = [];
        $sortArr =['pgm_id', 'desc'];

        // 类型树形条件检索
        if(isset($param['type']) && $param['type'] != 'all') {
            $where[] = ['pgm_type', 'in', $param['type']];                                 
        }

        if(isset($param['sort']) && !empty($param['sort'])) {
            $sortArr = explode(',', $param['sort']);
        }
        
        if (isset($param['name']) && !empty($param['name'])) $where[] = ['pgm_name', 'like', "%{$param['name']}%"];
        // var_dump($where);

        $matList = PgmInfoModel::pgmlibList($where, $param['offset'], $param['length'], $sortArr[0], $sortArr[1]);

        return $matList;
    }

    /**
     * 素材 新增，编辑
     */
    public function pgmlibAddEditSave($param)
    {
        $where = [];
        if(isset($param['pgm_id'])) {
            // 编辑
            $where[] = ['pgm_id', '=', $param['pgm_id']];
            unset($param['pgm_id']);
        } else {
            // 新增
            $adminLoginInfo = $this->adminLoginInfo();
            $param['creator'] = $adminLoginInfo['id'];
            $param['create_time'] = time();
        }       
     
        // var_dump($param);
        return PgmInfoModel::addEditSave($param, $where);
    }

    /**
     * 素材删除
     */
    public function pgmlibDelete($ids)
    {
        // 当ids 不为空时
        if(!empty($ids)) {            
            $res = PgmInfoModel::deleteData([['pgm_id', 'in', $ids]]);
            $where = [['pgm_id', 'in', $ids]];
            PgmInfoPlayModel::deleteData($where); // 删除节目播放信息
        } else {
            return [
                'code' => 0,
                'msg'  => '参数未定义'
            ];
        }

        return [
            'code' => $res ? 1 : 0,
            'msg'  => $res ? '删除成功' : '删除失败'
        ];
    }

    public function pgmplayList($param = []) 
    {
        $where = [];
        $sortArr =['play_id', 'asc'];

        if(isset($param['sort']) && !empty($param['sort'])) {
            $sortArr = explode(',', $param['sort']);
        }

        if(isset($param['pgm_id']) && !empty($param['pgm_id'])) {
            $where[] = ['pgm_id', '=', $param['pgm_id']];
        }

        $matList = PgmInfoPlayModel::pgmplayList($where, $param['offset'], $param['length'], $sortArr[0], $sortArr[1]);

        return $matList;
    }

    public function pgmplayAdd($param = [])
    {
        $count = 0;
        if (isset($param['pgm_id'])) {
            $count =  PgmInfoPlayModel::where([['pgm_id', '=', $param['pgm_id']]])->max('play_id');
            $param['play_id'] = $count + 1;
        }

        return PgmInfoPlayModel::addEditSave($param);
    }

    public function pgmplayEdit($param = [])
    {
        $where = [];
        if(isset($param['pgm_id']) && !empty($param['pgm_id'])) {
            $where[] = ['pgm_id', '=', $param['pgm_id']];
            unset($param['pgm_id']);
        }

        if(isset($param['play_id']) && !empty($param['play_id'])) {
            $where[] = ['play_id', '=', $param['play_id']];
            unset($param['play_id']);
        }

        if(empty($where) || count($where) != 2) {
            exception('条件错误');
        }

        return PgmInfoPlayModel::addEditSave($param, $where);
    }

    public function pgmplayDelete($rows) {
        if(!empty($rows)) {
            $where = [];            
            $where[] = ['pgm_id', '=', $rows['pgm_id']];
            $where[] = ['play_id', '=', $rows['play_id']];
            // 启用事务
            Db::startTrans();        
            try {
                $res = PgmInfoPlayModel::deleteData($where);
                PgmInfoPlanModel::deleteData($where);
                PgmInfoDetailModel::deleteData($where);
                Db::commit();
            } catch(\Exception $e) {
                Db::rollback();
                return ['code' => 0, 'msg' => $e->getMessage()];
            }

            return [
                'code' => $res ? 1 : 0,
                'msg'  => $res ? '删除成功' : '删除失败'
            ];
        } else {
            exception('参数异常！');
        }
    }

    public function pgmPlayPlan($param = []) 
    {
        $where = [];

        if(isset($param['pgm_id']) && !empty($param['pgm_id'])) {
            $where[] = ['pgm_id', '=', $param['pgm_id']];
        }

        if(isset($param['play_id']) && !empty($param['play_id'])) {
            $where[] = ['play_id', '=', $param['play_id']];
        }

        $pgmplanlist = PgmInfoPlanModel::pgmplanList($where);

        return $pgmplanlist;
    }

    public function pgmPlayPlanAdd($param = []) 
    {
        if(!isset($param['pgm_id']) || !isset($param['play_id'])) {
            exception('参数异常!');
        }

        $where = [];
        $where[] = ['pgm_id', '=', $param['pgm_id']];
        $where[] = ['play_id', '=', $param['play_id']];
        $where[] = ['dayofweek', '=', $param['dayofweek']];

        if(PgmInfoPlanModel::info($where)) {
            // 编辑
            unset($param['pgm_id']);
            unset($param['play_id']);
            unset($param['dayofweek']);
            return PgmInfoPlanModel::addEditSave($param, $where);
        } else {
            // 新增
            return PgmInfoPlanModel::addEditSave($param);
        }         
        // var_dump($param);  
    }

    public function pgmPlayDetailList($param = [])
    {
        $where = [];

        if(isset($param['pgm_id']) && !empty($param['pgm_id'])) {
            $where[] = ['pgm_id', '=', $param['pgm_id']];
        }

        if(isset($param['play_id']) && !empty($param['play_id'])) {
            $where[] = ['play_id', '=', $param['play_id']];
        }

        return PgmInfoDetailModel::pgmdetailList($where);
    }

    // 根据日期， 频道ID获取当天播放安排节目列表
    public function pgmLibDetailList($param)
    {
        // 先用 频道id 查询 t_pgm_info_play 表，查找到当前频道中所有节目

        return PgmInfoDetailModel::pgmInfoDayList($param);
    }

    public function pgmPlayDetailAdd($param = [])
    {
        if(!isset($param['pgm_id']) || !isset($param['play_id'])) exception('节目ID或播放ID主键丢失！');
        if(empty($param['pgm_id']) || empty($param['play_id'])) exception('节目ID或播放ID主键为空！');

        $where = [];
        $where[] = ['pgm_id', '=', $param['pgm_id']];
        $where[] = ['play_id', '=', $param['play_id']];

        // 启用事务
        Db::startTrans();
        try{
            PgmInfoDetailModel::deleteData($where);
            PgmInfoDetailModel::insertAll($param['list']);
            // 提交事务
            Db::commit();
        } catch(\Exception $e) {
            Db::rollback();
            exception($e->getMessage(), $e->getCode());
        }
        return true;       
    }

    public function pgmPlayDetailEdit($param = [])
    {
        if(!isset($param['list']) || empty($param['list'])) exception('无更新的项');
        // 启用事务
        Db::startTrans();
        try{ 
            foreach($param['list'] as &$v) {
                $where = [['seq', '=', $v['seq']]];
                unset($v['new_play_time']);
                unset($v['new_play_date']);
                PgmInfoDetailModel::dateUpdate($v, $where);
            } 
            // 提交事务
            Db::commit();
        } catch(\Exception $e) {
            Db::rollback();
            exception($e->getMessage(), $e->getCode());
        }
        return true;  
    }

    public function advlibList($param = []) {
        $where = [];
        $sortArr =['pgm_id', 'desc'];

        if(isset($param['flag'])) { 
            $where[] = ['cancel_flag', '=', $param['flag']];
        }        

        if(isset($param['sort']) && !empty($param['sort'])) {
            $sortArr = explode(',', $param['sort']);
        }

        if(isset($param['type']) && $param['type'] != 0) {
            $where[] = ['pgm_type', 'in', $param['type']];                                 
        }        

        if (isset($param['name']) && !empty($param['name'])) $where[] = ['pgm_name', 'like', "%{$param['name']}%"];

        $matList = AdvPgmInfoModel::advpgmList($where, $param['offset'], $param['length'], $sortArr[0], $sortArr[1]);

        return $matList;
    }

    /**
     * 素材 新增，编辑
     */
    public function advlibAddEditSave($param)
    {
        $where = [];
        if(isset($param['pgm_id'])) {
            // 编辑
            $where[] = ['pgm_id', '=', $param['pgm_id']];
            unset($param['pgm_id']);
        } else {
            // 新增
            $adminLoginInfo = $this->adminLoginInfo();
            $param['creator'] = $adminLoginInfo['id'];
            $param['create_time'] = time();
        }       
     
        // var_dump($param);
        return AdvPgmInfoModel::addEditSave($param, $where);
    }

    public function advlibDel($ids)
    {
        // 当ids 不为空时
        if(!empty($ids)) {
            $res = AdvPgmInfoModel::deleteData([['pgm_id', 'in', $ids]]);
        } else {
            return [
                'code' => 0,
                'msg'  => '参数未定义'
            ];
        }

        return [
            'code' => $res ? 1 : 0,
            'msg'  => $res ? '删除成功' : '删除失败'
        ];
    }

    public function channelgroup()
    {
        $channel_list = ChannelInfoModel::listsAll()->toArray();
        $pgmgroup_list = PgmGroupModel::listsAll()->toArray();
        
        $data = [];
        if($channel_list) {
            foreach($channel_list as $k => $v) {
                $data[$k]['value'] = $v['id'];
                $data[$k]['label'] = $v['channel_name'];
            }

            foreach($pgmgroup_list as &$c) {
                foreach($data as $d =>$f) {
                    if($c['channel_id'] == $f['value']) {
                        $data[$d]['children'][] = ['value' => $c['pgmgrp_id'], 'label' => $c['pgmgrp_name']];
                    }
                }
            }
        }
        return $data;
    }

    public function channelgrp($param)
    {
        $where = [];
        if(isset($param['channel']) && !empty($param['channel'])) {
            $where[] = ['channel_id', '=', $param['channel']];
            $list = PgmGroupModel::listsAll($where)->toArray();
        } else {
            $list = [];
        }

        $data = [];
        if(!empty($list)) {
            // 根据节目组ID 获取素材ID
            // 素材ID 统计素材总长度
            foreach($list as $k => $v) {
                $data[$k] = $v;
                $sum = PgmGroupDetailModel::pgmgrp_len([['pgmgrp_id', '=', $v['pgmgrp_id']]]); // 获取节目组实际长度
                $data[$k]['pgmgrp_len'] = $sum;
            }
        }


        return [
            'total' => count($data),
            'list' => $data
        ];
    }

    public function channelgroupAddEditSave($param)
    {
        $where = [];
        if(isset($param['pgmgrp_id'])) {
            // 编辑
            $where[] = ['pgmgrp_id', '=', $param['pgmgrp_id']];
            unset($param['pgmgrp_id']);
        }     

        return PgmGroupModel::addEditSave($param, $where);
    }

    public function channelgroupDel($ids)
    {
        // 当ids 不为空时
        if(!empty($ids)) {
            $res = PgmGroupModel::deleteData([['pgmgrp_id', 'in', $ids]]);
        } else {
            return [
                'code' => 0,
                'msg'  => '参数未定义'
            ];
        }

        return [
            'code' => $res ? 1 : 0,
            'msg'  => $res ? '删除成功' : '删除失败'
        ];
    }

    public function pgmgroupList($param) 
    {
        if (!isset($param['type'])) exception('节目组参数异常!');

        if(isset($param['ordername']) || isset($param['order'])) {
            $ordername = $param['ordername'] ?: 'seq';
            $order = $param['order'] == 'descending' ? 'desc' : 'asc';
        }

        $where = [];
        $where[] = ['pgmgrp_id', '=', $param['type']];

        return PgmGroupDetailModel::detailLists($where, $ordername, $order);
    }

    public function pgmgroupAdd($param)
    {
        $where = [];
        if(isset($param['pgmgrp_id'])){
            $where[] = ['pgmgrp_id', '=', $param['pgmgrp_id']];
        } else {
            exception('参数异常');
        }
        PgmGroupDetailModel::deleteData($where);

        $data = [];
        
        if (!empty($param['mat_id'])) {
            $matArr = explode(',', $param['mat_id']);
            foreach($matArr as $k => $v) {
                $data[$k]['mat_id'] = intval($v);
                $data[$k]['pgmgrp_id'] = intval($param['pgmgrp_id']);
                $data[$k]['seq'] = $k + 1;
            }
        }
        
        return PgmGroupDetailModel::insertAll($data);
    }
}